package com.pethospital.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pethospital.entity.Appointment;
import com.pethospital.entity.Review;
import com.pethospital.entity.Staff;
import com.pethospital.entity.User;
import com.pethospital.exception.BusinessException;
import com.pethospital.mapper.ReviewMapper;
import com.pethospital.service.AppointmentService;
import com.pethospital.service.ReviewService;
import com.pethospital.service.StaffService;
import com.pethospital.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 评价服务实现类
 */
@Slf4j
@Service
public class ReviewServiceImpl extends ServiceImpl<ReviewMapper, Review> implements ReviewService {

    @Resource
    private AppointmentService appointmentService;

    @Resource
    private UserService userService;

    @Resource
    private StaffService staffService;

    @Override
    public Review getReviewByAppointmentId(Long appointmentId) {
        if (appointmentId == null) {
            return null;
        }
        
        LambdaQueryWrapper<Review> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Review::getAppointmentId, appointmentId);
        
        Review review = getOne(queryWrapper);
        
        if (review != null) {
            // 填充用户和医生名称
            fillReviewExtraInfo(review);
        }
        
        return review;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addReview(Review review, Long userId) {
        log.info("添加评价: {}, 用户ID: {}", review, userId);

        // 获取预约信息
        Appointment appointment = appointmentService.getById(review.getAppointmentId());
        if (appointment == null) {
            throw new BusinessException("预约不存在");
        }

        // 验证是否是本人的预约
        if (!appointment.getUserId().equals(userId)) {
            throw new BusinessException("无权评价此预约");
        }

        // 验证预约状态是否是已完成
        if (appointment.getStatus() != 2) {
            throw new BusinessException("只能评价已完成的预约");
        }

        // 检查是否已评价
        Review existingReview = getReviewByAppointmentId(review.getAppointmentId());
        if (existingReview != null) {
            throw new BusinessException("该预约已评价，不能重复评价");
        }

        // 设置评价信息
        review.setUserId(userId);
        review.setStaffId(appointment.getStaffId());
        review.setCreateTime(LocalDateTime.now());
        review.setUpdateTime(LocalDateTime.now());

        // 评分范围验证 (1-5)
        if (review.getScore() < 1 || review.getScore() > 5) {
            throw new BusinessException("评分范围为1-5");
        }

        // 保存评价
        save(review);
        
        log.info("评价添加成功, ID: {}", review.getId());
        return review.getId();
    }

    @Override
    public Page<Review> getUserReviews(Long userId, int page, int size) {
        log.info("获取用户评价列表, 用户ID: {}, 页码: {}, 每页: {}", userId, page, size);
        
        Page<Review> reviewPage = page(new Page<>(page, size), new LambdaQueryWrapper<Review>()
                .eq(Review::getUserId, userId)
                .orderByDesc(Review::getCreateTime));
        
        // 填充评价额外信息
        fillReviewsExtraInfo(reviewPage.getRecords());
        
        return reviewPage;
    }

    @Override
    public Page<Review> getStaffReviews(Long staffId, int page, int size) {
        log.info("获取医护人员评价列表, 医护人员ID: {}, 页码: {}, 每页: {}", staffId, page, size);
        
        Page<Review> reviewPage = page(new Page<>(page, size), new LambdaQueryWrapper<Review>()
                .eq(Review::getStaffId, staffId)
                .orderByDesc(Review::getCreateTime));
        
        // 填充评价额外信息
        fillReviewsExtraInfo(reviewPage.getRecords());
        
        return reviewPage;
    }
    
    /**
     * 填充评价额外信息
     * @param reviews
     */
    private void fillReviewsExtraInfo(Iterable<Review> reviews) {
        if (reviews == null) {
            return;
        }
        
        for (Review review : reviews) {
            fillReviewExtraInfo(review);
        }
    }
    
    /**
     * 填充单个评价的额外信息
     * @param review
     */
    private void fillReviewExtraInfo(Review review) {
        if (review == null) {
            return;
        }
        
        // 填充用户名
        if (review.getUserId() != null) {
            User user = userService.getById(review.getUserId());
            if (user != null) {
                review.setUserName(user.getNickname());
            }
        }
        
        // 填充医生名
        if (review.getStaffId() != null) {
            Staff staff = staffService.getById(review.getStaffId());
            if (staff != null) {
                review.setStaffName(staff.getName());
            }
        }
    }
} 